package com.zastoupil.pgc.blueprint_pattern.xml;

import java.io.File;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * XML file reader for the XML configuration file. Implements the singleton
 * pattern.
 * 
 * @see XMLConfig
 * 
 * @author Peter Zastoupil
 * 
 */
public class XMLConfigReader {

	private static final String CONFIG_PATH = "config/xmlconfig.xml";

	private static XMLConfig _config;

	/**
	 * 
	 * @return an object representation of the XML configuration file associated
	 *         with this project setup
	 */
	public static XMLConfig getXMLConfig() {
		if (_config == null) {
			XMLConfigReader.initConfig();
		}
		return _config;
	}

	// Tries to read an object from the XMLConfig.xml file. If this file does
	// not exist at the expected location, creates a configuration file with
	// default values
	private static void initConfig() {

		try {

			JAXBContext context = JAXBContext.newInstance(XMLConfig.class);

			File configFile = new File(CONFIG_PATH);

			if (configFile.exists()) {

				// Read given config file
				Unmarshaller configUnmarshaller = context.createUnmarshaller();

				_config = (XMLConfig) configUnmarshaller.unmarshal(configFile);

			} else {

				// Create new config object with default values
				_config = new XMLConfig();
				_config.setBlueprintDirectoryPath("res/xml/blueprints/");
				_config.setBlueprintFileSuffix("-blueprint.xml");
				_config.setModifierDirectoryPath("res/xml/modifiers/");
				_config.setModifierFileSuffix("-modifier.xml");
				_config.setFactoryDirectoryPath("res/xml/factories/");
				_config.setFactoryFileSuffix("-factory.xml");

				// Marshal created config object to an xml file
				configFile.createNewFile();

				Marshaller configMarshaller = context.createMarshaller();

				configMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
						true);

				configMarshaller.marshal(_config, configFile);

			}

		} catch (JAXBException e) {
			System.err.println("Problem encountered in XML binding");
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Problem encountered in file creation");
			e.printStackTrace();
		}

	}

}
